package com.qy.securitydemo.service;

import com.qy.securitydemo.dal.SysUserMapper;
import com.qy.securitydemo.dal.UserRoleMapper;
import com.qy.securitydemo.model.SysRole;
import com.qy.securitydemo.model.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HXB
 * @Title:
 * @Package
 * @Description:
 * @date 2019-11-0811:24
 */
public class CustomUserService implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserRepository;
    @Autowired
    private UserRoleMapper userRoleService;

//    @Override
//    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        SysUser user = sysUserRepository.findByUsername(s);
//        if (user == null) {
//            throw new UsernameNotFoundException("用户名不存在");
//        }
//        System.out.println("s:"+s);
//        System.out.println("username:"+user.getUsername()+";password:"+user.getPassword());
//        return user;
//    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserRepository.findByUsername(username);
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
        List<SysRole> roles = userRoleService.getRoleByUser(user.getId());
        for(SysRole role:roles)
        {
            //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            System.out.println(role.getName());
        }
        return new User(user.getUsername(),
                user.getPassword(), authorities);
    }


}